﻿using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using WorkFlowCore.Plugins;
using WorkFlowCore.UserSelectors;

namespace WorkFlowCore.Framework.UserSelectors
{
    [UserSelector("默认成员选择器")]
   
    [PluginDescription("参数：users=[url,用户字典] 如果传url，接收 post 请求，传参 {SelectionId:string selections 中的Id,Expression:string 表达式,WorkTask:object 当前流程实例,CurrentStep:object 当前审批步骤 }，不传时，默认构造创建人id返回。返回格式参考 【用户数组】")]
    [PluginDescription("用户数组：[{\"Id\":\"\",Name:\"\"}]")]
    [PluginDescription("用户字典：{\"SelectionId\":[{Id:\"\",Name:\"\"}]} SelectionId 值为 selections 中的Id")]
    [PluginDescription("重要说明：这里\"创建人\"传参中的  SelectionId 实际为 流程创建人用户id")]
    public class DefaultUserSelector : IUserSelector,IDefaultUserSelector, IConfigurable
    {
        ConfigureContext configureContext;
        public Task Configure(ConfigureContext configureContext)
        {
            this.configureContext = configureContext;
            return Task.CompletedTask;
        }

        public List<string> GetDefaultSelectionIds()
        {
            return new List<string>() { "creator" };
        }

        public List<Selection> GetSelections()
        {
            return new List<Selection>()
            {
                new Selection{ Id="creator", Name="创建人"},
            };
        }

        public List<User> GetUsers(SelectorInput input)
        {
            var result = new List<User>();
            try
            {
                switch (input.SelectionId)
                {
                    case "creator":
                    default:
                        var usersParemeter = configureContext.Parameters.GetOrDefault("users") ?? "";
                        if (usersParemeter.IsNullOrWhiteSpace())
                        {
                            var user = UserList.GetUserById(input.WorkTask?.CreatedUserId);
                            result.Add(new User { Id = input.WorkTask.CreatedUserId, Name = user?.Name });
                        }
                        else
                        {
                            //这里默认已创建人id去查创建人
                            var copyInput = JObject.Parse(JsonConvert.SerializeObject(input));
                            copyInput["SelectionId"] = input.WorkTask?.CreatedUserId;
                            if (usersParemeter.StartsWith("http"))
                            {
                                var httpClient = new HttpClient();
                                var resp = httpClient.PostAsync(usersParemeter, new StringContent(copyInput.ToString(), Encoding.UTF8, "application/json")).Result;
                                var data = resp.Content.ReadAsStringAsync().Result;
                                return JsonConvert.DeserializeObject<List<User>>(data);
                            }
                            else
                            {
                                var jObject = JObject.Parse(usersParemeter);
                                return JsonConvert.DeserializeObject<List<User>>(jObject[input.WorkTask?.CreatedUserId].ToString());
                            }
                        }


                        break;
                }
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex.Message);
                Console.Error.WriteLine(ex.StackTrace);
            }
            return result;
        }
    }
}
